import { resolve } from 'path'

import { defineConfig } from 'vite'
import viteCompression from 'vite-plugin-compression'
import visualizer from 'rollup-plugin-visualizer'

import vue from '@vitejs/plugin-vue'
import legacy from '@vitejs/plugin-legacy'

import Components from 'unplugin-vue-components/vite'
import {
  ArcoResolver,
  NaiveUiResolver,
  ElementPlusResolver,
  VueUseComponentsResolver
} from 'unplugin-vue-components/resolvers'

// https://vitejs.dev/config/
export default defineConfig(({ command }) => {
  const assetsDir = 'static'
  const config = {
    resolve: {
      alias: [
        {
          find: /\/@\//,
          replacement: resolve(__dirname, './src') + '/'
        }
      ]
    },
    build: {
      assetsDir,
      rollupOptions: {
        output: {
          entryFileNames: `${assetsDir}/[hash].js`,
          chunkFileNames: `${assetsDir}/[hash].js`,
          assetFileNames: `${assetsDir}/[hash].[ext]`
        }
      }
    },
    server: {
      host: '0.0.0.0'
    }
  }
  const plugins = [
    vue(),
    Components({
      deep: true,
      resolvers: [
        ArcoResolver({
          resolveIcons: true
        }),
        NaiveUiResolver(),
        ElementPlusResolver(),
        VueUseComponentsResolver()
      ]
    }),
    legacy({
      targets: ['ie >= 11'],
      additionalLegacyPolyfills: [
        'unfetch/polyfill/polyfill.mjs', // fetch
        'matchmedia-polyfill/matchMedia.addListener', // vue-mq
        'regenerator-runtime/runtime' // ie11
      ]
    })
  ]

  if (command === 'build') {
    if (process.env.npm_config_report) {
      // npm run build --report
      // npm_config_report=true yarn build
      plugins.push(visualizer({
        open: true
      }))
    }
    plugins.push(viteCompression({
      algorithm: 'brotliCompress'
    }))
  }

  return {
    ...config,
    plugins
  }
})
